The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex
statements. However, this does not mean that parentheses should be gratuitously added around every operation.
Parentheses are not needed:
- with a unary operator, except when
!
is used as left operand in comparison expressions
- when all the operators in an expression are the same
- when only a single operator is involved
- around the right-hand side of an assignment operator unless the right-hand side itself contains an assignment
Parentheses are needed:
- in the condition of a ternary operator if it uses operators
- when overloaded shift operator
<<
or >>
is used in an expression with comparison operators
Noncompliant code example
x = a + b;
x = a * -1;
x = a + b + c;
x = f ( a + b, c );
x = a == b ? a : a - b; // Noncompliant
x = a + b - c + d; // Noncompliant
x = a * 3 + c + d; // Noncompliant
if (a = f(b,c) == true) { ... } // Noncompliant; == evaluated first
x - b ? a : c; // Noncompliant; "-" evaluated first
s << 5 == 1; // Noncompliant; "<<" evaluated first
Compliant solution
x = a + b;
x = a * -1;
x = a + b + c;
x = f ( a + b, c );
x = ( a == b ) ? a : ( a - b );
x = ( a + b ) - ( c + d );
x = ( a * 3 ) + c + d;
if ( (a = f(b,c)) == true) { ... }
(x - b) ? a : c; // Compliant
(s << 5) == 1; // Compliant